using System;
using System.IO;
using System.Web;
using System.Collections;
using newtelligence.DasBlog.Runtime;

namespace newtelligence.DasBlog.Web.Core
{
	/// <summary>
	/// Summary description for TitleHandler.
	/// </summary>
	public class TitleMapperModule : IHttpModule
	{
		static readonly string[] HttpHandlerStrings = new string[] {"CaptchaImage.aspx", "aggbug.ashx", "blogger.aspx", "pingback.aspx", "trackback.aspx", "get_aspx_ver"};
		private EventHandler onBeginRequest;

		public TitleMapperModule()
		{
			onBeginRequest = new EventHandler(this.HandleBeginRequest);
		}

		public void Init(HttpApplication context)
		{
			context.BeginRequest += onBeginRequest;
		}

		public void Dispose()
		{
		}

		private void HandleBeginRequest( object sender, EventArgs evargs )
		{
			HttpApplication app = sender as HttpApplication;
			string requestUrl = "";

			if ( app != null )
			{
				requestUrl = app.Context.Request.Url.PathAndQuery;
			
				if (requestUrl.IndexOf(",") == -1 & requestUrl.IndexOf("?") == -1 )
				{
					// TODO: there has to be a way to also see if the request is from an HttpHander since File.Exists won't work.
					if (requestUrl.EndsWith(".aspx") && !File.Exists(app.Context.Server.MapPath(app.Context.Request.FilePath)))
					{
						ILoggingDataService logService = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());
						IBlogDataService dataService = BlogDataServiceFactory.GetService(SiteConfig.GetContentPathFromCurrentContext(), logService);
                    
						string title = app.Context.Request.Url.Segments[app.Context.Request.Url.Segments.Length - 1];

						if (Array.IndexOf(HttpHandlerStrings, title) == -1 )
						{
							title = title.Replace(".aspx", "");
							title = title.Replace("+", "");
							title = title.Replace(" ", "");

							Entry entry = dataService.GetEntry( title );
							if ( entry != null )
							{
								requestUrl = "Permalink.aspx?guid=" + title;
								app.Context.RewritePath(requestUrl);
							}
						}
					}
				}
			}
		}
	}
}
